package com.xiaomai.controller;


import com.xiaomai.entity.User;
import com.xiaomai.service.UserService;
import com.xiaomai.util.JwtHelper;
import com.xiaomai.util.Result;
import com.xiaomai.util.ResultCodeEnum;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.LinkedHashMap;
import java.util.Map;

@RestController
@Api(tags = "用户信息接口")
@RequestMapping("/user")
public class UserController {

    @Resource
    private UserService userService;

    //修改用户信息
    @ApiOperation("修改用户信息")
    @PutMapping
    public Result update(@RequestBody User user){
        userService.updateById(user);
        return Result.ok();
    }


    //提取用户信息
    @ApiOperation("提取用户信息")
    @GetMapping("/getInfo")
    public Result getInfoByToken(@RequestHeader("token") String token){
        boolean expiration = JwtHelper.isExpiration(token);
        if (expiration) {
            System.out.println("抱歉，已经过期了");
            return Result.build(null, ResultCodeEnum.LOGIN_AUTH);
        }
        //从token中解析出用户id和用户类型
        String userId = JwtHelper.getUserId(token);

        Map<String,Object> map = new LinkedHashMap<>();
        User user = userService.getById(userId);
        map.put("user",user);
        return Result.ok(map);
    }

    //用户登陆
    @ApiOperation("用户登陆")
    @PostMapping("/login")
    public Result login(@RequestBody User user){
        //加密传进来的密码
        user.setPassword(DigestUtils.md5DigestAsHex(user.getPassword().getBytes()));
        //根据传进来的ID查询用户
        User result_user = userService.getById(user.getId());
        //判断是否存在 不存在直接返回
        if(result_user == null){
            return Result.fail().message("查无此账号");
        }
        //准备一个Map用户存放相应的数据
        Map<String, Object> map = new LinkedHashMap<>();
        //存在 校验密码
        if(result_user.getPassword().equals(user.getPassword())){
            String token = JwtHelper.createToken(user.getId(), user.getUsername());
            map.put("token", token);
            return Result.ok(map);
        }else{
            return Result.fail().message("密码错误");
        }
    }

    //用户注册
    @ApiOperation("用户注册")
    @PostMapping("/register")
    public Result<User> register(@RequestBody User user){
        //加密用户输入的密码
        user.setPassword(DigestUtils.md5DigestAsHex(user.getPassword().getBytes()));
        //保存用户
        boolean isSuccess = userService.save(user);
        if(isSuccess){
            //成功则返回用户信息--自动生成的id会映射到传进去的对象中
            return Result.ok(user);
        }else{
            return Result.fail();
        }
    }


}